class ApplicationController < ActionController::Base
  before_filter :require_login
  skip_before_filter :require_login, :only => [:login]
  
  def login
    if (params.has_key?(:username) && params.has_key?(:pwd))
      user = User.authenticate(params[:username], params[:pwd])
      if user
        jobsite = Jobsite.find(user.jobsite_id)
        @device = Device.find_by_user_id(user.id)
        
        if @device
          rtn_json({'status' => '200', 'username' => user.username, 'jobsitename' => jobsite.name, 'jobsiteid' => user.jobsite_id, 'userid' => user.id, 'deviceid' => @device.id})
        else
          rtn_json({'status' => '200', 'username' => user.username, 'jobsitename' => jobsite.name, 'jobsiteid' => user.jobsite_id, 'userid' => user.id, 'deviceid' => 1})
        end
      else
        rtn_json({'error' => "Invalid username or password"})
      end
    else
      rtn_json({'error' => 'must provide username and password'})
    end
  end
  
  private
 
  def require_login
    if (params.has_key?(:username) && params.has_key?(:pwd))
      user = User.authenticate(params[:username], params[:pwd])
      if user
  
      else
        rtn_json({'error' => "Invalid username or password"})
      end
    else
      rtn_json({'error' => 'must provide username and password'})
    end
  end
  
  def rtn_json(obj)
    respond_to do |format|
      format.html{render json: obj, :callback => params[:callback]}
      format.json{render json: obj, :callback => params[:callback]}
    end
  end

end
